import { useRequest } from 'ahooks';
import { useSearchParams } from 'react-router-dom';
import type { YmTreeProps } from 'ym-design';
import { YmTree } from 'ym-design';

import { useAppSelector } from '@/redux/store';

import { safeGovernanceTreeDataByAss } from '@/api/codeApi';
import { getTreeByList } from '@/utils';
import { isEmpty } from 'lodash-es';

interface PropsType {
  orgId: string;
  setOrg(value: any): void;
  type: string;
  allNum?: string;
}

export const OrgTree: React.FC<PropsType> = (props) => {
  const { orgId, setOrg, type } = props;
  const [sp] = useSearchParams();
  const urlOrgId = sp.get('orgId');
  const { entId } = useAppSelector((state) => ({
    entId: state.loginEnt.entId,
  }));

  const { data } = useRequest(
    async () => {
      const { data: list } = await safeGovernanceTreeDataByAss({
        associationId: entId,
        pageIndex: 1,
        pageSize: 999,
      });
      const rootNode = list.find((v) => v.entId === entId);
      const tree = getTreeByList({
        list,
        parentId: rootNode!.pid,
        parentKey: 'pid',
        key: 'orgId',
      });
      return {
        root: rootNode,
        tree,
        list,
      };
    },
    {
      onSuccess(data) {
        const urlOrg = data.list.find((v) => v.entId === urlOrgId);
        setOrg(urlOrg || data.root);
      },
    },
  );

  const onSelect: YmTreeProps['onSelect'] = (selectedKeys, info) => {
    setOrg(info.node);
  };

  return (
    <>
      {!isEmpty(data?.tree) && (
        <div>
          <YmTree
            treeSelectable
            defaultExpandAll
            selectedKeys={[orgId]}
            fieldNames={{
              title: 'orgName',
              key: 'entId',
              children: 'children',
            }}
            onSelect={onSelect}
            treeData={data?.tree ?? []}
            titleRender={(node: any) => {
              return (
                <div style={{ padding: '4px 8px' }} className="flexr alc">
                  <span style={{ textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' }}>
                    {node.orgName}
                  </span>
                  ({node[`${type}Num`]})
                </div>
              );
            }}
          />
        </div>
      )}
    </>
  );
};
